import json

from flask import Blueprint, request
from pypinyin import lazy_pinyin

from .models import City, Province

city_bp = Blueprint('city', __name__, url_prefix='/city')

@city_bp.route('/')
def list_cities():

    page_no = request.args.get('page_no', 1, type=int)  # 获取页码参数
    page_size = request.args.get('page_size', 20, type=int)  # 每页数量

    # 执行分页查询
    pagination = City.query.paginate(
        page=page_no,
        per_page=page_size,
        error_out=False  # 当页码超出范围时返回空而不是404
    )

    return {
        'cities': [city.to_dict() for city in pagination.items],
        'total': pagination.total,
        'page_total': pagination.pages,
        'page_no': pagination.page,
        'page_size': pagination.per_page
    }



import re

def is_three_letters(s):
    return bool(re.fullmatch(r'^[A-Za-z]{3}$', s))


@city_bp.route('/selector')
def list_cities_selector():
    cities = City.query.all()
    provinces_set = set()
    for city in cities:
        p = Province(city.province_id, city.province_name, ''.join(lazy_pinyin(city.province_name)))
        provinces_set.add(p)

    provinces_list = list(provinces_set)
    print(type(provinces_list))
    for p in provinces_list:
        print(type(p))
        json.dumps(p.to_dict())

    return_val = [p.to_dict() for p in provinces_list]
    for p in return_val:
        for city in cities:
            # print(p)
            if p['id'] == str(city.province_id) and is_three_letters(city.city_code):
                p['children'].append(city.to_dict())

    return return_val
